package kyssion.leetcode.num101_150;

import kyssion.leetcode.util.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class code102_层次遍历二叉树 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> listList = new ArrayList<>();
        if (root == null) {
            return listList;
        }
        List<TreeNode> old = new ArrayList<>();
        List<TreeNode> newNode = new ArrayList<>();
        old.add(root);
        while (old.size() > 0) {
            List<Integer> list = new ArrayList<>();
            for (TreeNode treeNode : old) {
                if (treeNode != null) {
                    list.add(treeNode.val);
                    if (treeNode.left != null) {
                        newNode.add(treeNode.left);
                    }
                    if (treeNode.right != null) {
                        newNode.add(treeNode.right);
                    }
                }
            }
            listList.add(list);
            old = newNode;
            newNode = new ArrayList<>();
        }
        return listList;
    }

    /**
     * 使用队列逻辑更加清晰
     * @param root
     * @return
     */
    public List<List<Integer>> levelOrder2(TreeNode root) {

        List<List<Integer>> ans = new ArrayList<List<Integer>>();

        if(root == null)
            return ans;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while(!queue.isEmpty())
        {
            List<Integer> list = new ArrayList<Integer>();
            int size = queue.size();
            for(int i = 0 ;i < size; i++)
            {
                TreeNode node = queue.poll();
                list.add(node.val);
                if(node.left != null)
                {
                    queue.offer(node.left);
                }
                if(node.right!=null)
                {
                    queue.offer(node.right);
                }
            }
            ans.add(list);
        }
        return ans;
    }
}
